import java.lang.*;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


//这是一个文件工具类
public class FileUtils{

    public static void saveImage(String url, String savePath) throws IOException {
        URL imageUrl = new URL(url);
        FileUtils.ensureDirectoryExists(savePath);
        try (InputStream in = imageUrl.openStream();
             FileOutputStream out = new FileOutputStream(savePath)) {
            byte[] buffer = new byte[4*1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
    }
    public static void ensureDirectoryExists(String dirPath){
        File outFile=new File(dirPath);
        File dir=outFile.getParentFile();
        dir.mkdirs();
    }

    public static void appendLog(String log) throws IOException {
        Path logFile = Paths.get("download_log.txt"); // 改成当前目录
        System.out.println("日志写入路径: " + logFile.toAbsolutePath()); // 调试用
        String line = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
                + "  " + log + System.lineSeparator();
        Files.writeString(logFile, line,
                StandardOpenOption.CREATE,
                StandardOpenOption.APPEND);
    }
}
